package com.htime.intercepter;

import com.htime.domain.CommonConst;
import com.htime.domain.CommonRes;
import com.htime.domain.User;
import com.htime.domain.ValidationModel;
import com.htime.exception.RcException;
import com.htime.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by HTime on 2017/3/5.
 */
@Component
public class AccessTokenVerifyInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    ValidationService validationService;

    @Autowired
    UserService userService;

    private Logger logger = Logger.getLogger(getClass());

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.info("AccessToken executing ...");
        boolean flag = false;

        String requestUrl = request.getRequestURL().toString();
        if(null != requestUrl && requestUrl.contains("/auth")) {
            return true;
        }
        //TODO delete
        if(null != requestUrl && requestUrl.contains("/cookie")) {
            return true;
        }
        //TODO delete
        if(null != requestUrl && requestUrl.contains("/sessionInCookie")) {
            return true;
        }
        // token
        String accessToken = request.getHeader("token");
        if (StringUtils.isNotBlank(accessToken)) {
            ValidationModel model = new ValidationModel();

            // 验证token
            Boolean isOk = validationService.verifyAccessToken(accessToken, model);

            // 用户验证
            if (isOk) {
                User user = userService.getUserById(model.getUid());
                if(user != null) {
                    request.setAttribute(CommonConst.PARAM_USER, user);
                    logger.info("AccessToken SUCCESS ...  user:" + user.getUserName() + " - " + accessToken);
                    flag = true;
                }
            }
        }

        if (!flag) {
            throw new RcException(CommonRes.RES_NEED_AUTH, "auth fail");
        }

        return flag;
    }

}
